package com.learn.mvc.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.learn.mvc.action.Action;
import com.learn.mvc.pojo.BaseForm;
import com.learn.mvc.pojo.ConfigBean;
import com.learn.mvc.utils.ReflectUtils;
import com.learn.mvc.utils.StrutsConfig;

public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String path = this.getPath(req.getServletPath());
		Map<String, ConfigBean> configMap = StrutsConfig.getXmlBeanMap();
		ConfigBean bean = configMap.get(path);
		try {
			Action action = ReflectUtils.getActionInstance(bean.getActionClass());
			BaseForm form = ReflectUtils.fullFormInstance(bean, req);
			String result = action.execute(form);
			String url = bean.getMap().get(result);
			RequestDispatcher dispatcher = req.getRequestDispatcher(url);
			dispatcher.forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	public String getPath(String servletPath) {
		return servletPath.split("\\.")[0];
	}

	@Override
	public void init() throws ServletException {
		StrutsConfig.parseXml();
	}

	public Action getActionInstance(String className) throws Exception {
		Action baseAction = null;

		return baseAction;
	}
}
